package com.guigu.eduservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageInfo;
import com.guigu.common.utils.R;
import com.guigu.eduservice.entity.BargainIntention;
import com.guigu.eduservice.entity.Equipment;
import com.guigu.eduservice.entity.EquipmentReservation;
import com.guigu.eduservice.entity.Order;
import com.guigu.eduservice.service.BargainIntentionService;
import com.guigu.eduservice.service.EquipmentReservationService;
import com.guigu.eduservice.service.EquipmentService;
import com.guigu.eduservice.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/eduservice/bargainintention")
public class BargainIntentionController {

    @Autowired
    private BargainIntentionService bargainIntentionService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private EquipmentReservationService equipmentReservationService;

    @PostMapping("/addBargainIntention")
    public boolean addBargainIntention(@RequestBody BargainIntention bargainIntention) {
        System.out.println("bargainIntention"+ bargainIntention);
        bargainIntention.setBargainStatus(0);
        return bargainIntentionService.save(bargainIntention);
    }
    //获取砍价列表，根据买家用户ID来查询
    @GetMapping("/getBargainIntentionListByUserId/{userId}")
    public R getBargainIntentionListByUserId(@PathVariable("userId") Long userId) {
        if (userId == null){return R.error().message("用户ID不能为空");}
        LambdaQueryWrapper<BargainIntention> bargainIntentionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bargainIntentionLambdaQueryWrapper.eq(BargainIntention::getUserId, userId);
        List<BargainIntention> list = bargainIntentionService.list(bargainIntentionLambdaQueryWrapper);
        return R.ok().data("list",list);
    }
    //根据设备ID查询砍价列表
    @GetMapping("/getBargainIntentionListByEquipmentId/{equipmentId}")
    public R getBargainIntentionListByEquipmentId(@PathVariable("equipmentId") Long equipmentId) {
        if (equipmentId == null){return R.error().message("设备ID不能为空");}
        LambdaQueryWrapper<BargainIntention> bargainIntentionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bargainIntentionLambdaQueryWrapper.eq(BargainIntention::getEquipmentId, equipmentId);
        List<BargainIntention> list = bargainIntentionService.list(bargainIntentionLambdaQueryWrapper);
        return R.ok().data("list",list);
    }

    @PutMapping("/updateBargainIntention")//买家修改
    public boolean updateBargainIntention(@RequestBody BargainIntention bargainIntention) {
        if (bargainIntention.getBargainId() == null){
            return false;
        }
        return bargainIntentionService.updateById(bargainIntention);
    }
    @PutMapping("/updateBargainIntentionByShangHu")
    public R updateBargainIntentionByShangHu(@RequestBody BargainIntention bargainIntention){
        //卖家修改
        //先根据砍价ID查询，判断商户砍价状态
        if (bargainIntention.getBargainId() == null){
            return R.error().message("砍价ID不能为空");
        }
        if (bargainIntention.getBargainStatus() != 0){
            //添加卖家回复时间
            bargainIntention.setReplyTime(new Date());
        }
        boolean b = bargainIntentionService.updateById(bargainIntention);
        if (!b) return R.error().message("修改失败");
        boolean b1 = bargainIntentionService.updateBargainIntention(bargainIntention.getBargainId());
        return b1 ? R.ok().message("修改成功") : R.error().message("修改失败");
    }
    //删除砍价
    @DeleteMapping("/deleteBargainIntention/{bargainId}")
    public R deleteBargainIntention(@PathVariable("bargainId") Long bargainId) {
        // 1. 入参非空校验（原有逻辑保留，补充日志）
        if (bargainId == null) {
            return R.error().message("砍价ID不能为空");
        }

        // 2. 查询砍价意向 + 非空校验
        BargainIntention byId = bargainIntentionService.getById(bargainId);
        if (byId == null) {
            return R.error().message("砍价不存在");
        }

        // 3. 关键字段非空校验（避免后续条件拼接null，或误改数据）
        Long buyerId = byId.getUserId();
        Long equipmentId = byId.getEquipmentId();
        Integer bargainStatus = byId.getBargainStatus();

        if (buyerId == null) {
            return R.error().message("砍价信息不完整，无法删除");
        }
        if (equipmentId == null) {
            return R.error().message("砍价信息不完整，无法删除");
        }
        // 校验砍价状态非空（避免null == 1 抛空指针）
        if (bargainStatus == null) {
            return R.error().message("砍价状态异常，无法删除");
        }

        // 4. 业务规则校验：状态为1（商户已同意）时，先处理关联数据再删砍价
        if (bargainStatus == 1) {
            try {
                // 4.1 删除关联订单（条件：买家ID+设备ID，双重校验避免误删）
                LambdaQueryWrapper<Order> orderWrapper = new LambdaQueryWrapper<>();
                orderWrapper.eq(Order::getBuyerId, buyerId)
                        .eq(Order::getEquipmentId, equipmentId);
                boolean removeOrder = orderService.remove(orderWrapper);
                // 4.2 删除关联预定表（同订单条件）
                LambdaQueryWrapper<EquipmentReservation> reservationWrapper = new LambdaQueryWrapper<>();
                reservationWrapper.eq(EquipmentReservation::getUserId, buyerId)
                        .eq(EquipmentReservation::getEquipmentId, equipmentId);
                boolean removeReservation = equipmentReservationService.remove(reservationWrapper);
                // 4.3 恢复设备状态为「已上架」（equipmentId已校验非空，避免误改）
                LambdaUpdateWrapper<Equipment> equipmentWrapper = new LambdaUpdateWrapper<>();
                equipmentWrapper.eq(Equipment::getEquipmentId, equipmentId)
                        .set(Equipment::getStatus, 1);
                boolean updateEquipment = equipmentService.update(equipmentWrapper);
                if (!updateEquipment) {
                    throw new RuntimeException("恢复设备状态失败，删除终止"); // 抛异常触发事务回滚
                }
            } catch (Exception e) {
                return R.error().message("删除失败：关联数据处理异常");
            }
        }

        // 5. 最后删除砍价意向（确保关联数据处理完成后再删主数据）
        boolean removeBargain = bargainIntentionService.removeById(bargainId);
        if (!removeBargain) {
            return R.error().message("删除失败");
        }

        return R.ok().message("删除成功");
    }

    @PostMapping("/getBargainIntentionList/{pageNo}/{pageSize}")
    public PageInfo<BargainIntention> getBargainIntentionList(@PathVariable("pageNo") int pageNo,
                                                              @PathVariable("pageSize") int pageSize) {
        return bargainIntentionService.getBargainIntentionList(pageNo, pageSize);
    }

}
